# -*- coding: utf-8 -*-
# @Time    : 2024/11/7 下午2:41
# @Author  : xiaowanzi
# @File    : upload_data.py
import ast
import base64
import re
import os
import traceback
import requests
from configobj import ConfigObj
from base.http_tools import http_post
from base.project_path import get_project_path

"""
测试报告入库
测试log入库
"""

project_path = get_project_path()
conf_ini = project_path + "\\config.ini"
config = ConfigObj(conf_ini, encoding='UTF8')
Log_path = 'logPath'


class Upload(object):
    def init__(self):
        """初始化 方法名(methodName)"""
        self.methodName = None
        self.className = None

    def assert_code(self, response):
        """
        断言请求和响应的code值
        :param response: 响应结果
        :return:
        """
        try:
            assert response.status_code == 200
            assert response.json()["code"] == 200
        except Exception as e:
            print(traceback.format_exc())

    def uploadImage(self, fileName, fileFormat, fileData):
        """
        錯误截图入库
        :param fileName:文件名称
        :param fileFormat:交件格式
        :param fileData:文件数据
        :return:入库截图的ID
        """
        url = config[Log_path]["uploadStatUrl"] + 'file/uploadFile'
        json = {
            "file_name": "{}".format(fileName),
            "file_format": "{}".format(fileFormat),
            "file_data": "{}".format(fileData),
        }
        response = requests.post(url, json=json)
        assert response.status_code == 200
        assert response.json()["code"] == 200
        return response.json()["data"]["id"]

    def getImageID(self):
        """
            获取错误截图
        :return:base64格式的截图内容的ID列表信息
        """
        path = os.path.dirname(os.path.dirname(__file__)) + "\\images\\error_img"
        r = re.compile(r'{}_{}.*'.format(self.className, self.methodName))  # 正则匹配错误截图文件
        imgListID = []
        try:
            for root, dirs, files in os.walk(path):
                imgList = [os.path.join(root, x) for x in files if r.findall(x)]
                if imgList:
                    for img in imgList:
                        with open(img, "rb") as file:
                            data = file.read()
                            imgbase64 = base64.b64encode(data).decode()
                        listname = img.split(".")
                        imgId = self.uploadImage(listname[0].split("\\")[-1], listname[1], imgbase64)
                        imgListID.append(imgId)
                    return imgListID
        except Exception as e:
            print(traceback.format_exc())
            return imgListID

    def caseStatus(self, status):
        """
        根据执行结果返回对应的状态码
        :param status:执行的结果
        :return:执行结果状态码
        """
        if status == "True":
            caseStats = 0
        elif status == "False":
            caseStats = 1
        elif status == "Skip":
            caseStats = 2
        else:
            caseStats = 3
        return caseStats

    def upload_report(self, data: dict, startTime, endTime, id):
        """
        测试报告入库
        :param data: 测试报告数据
        :param startTime:始时间
        :param endTime:结束时间
        :param id:以run_id对应
        :return:响应结果
        """

        caseClass = data['caseClass']
        caseMethod = data['caseMethod']
        self.methodName = data['caseId']
        self.className = data['caseClass']
        caseId = data['caseId']
        caseName = data['caseName']
        imageListID = []
        caseException = ''
        projectId = ''
        projectVersion = ''
        caseDescription = data['caseDescription']
        projectRunId = data['projectRunId']
        performIpLists = ast.literal_eval(data['performIpList'])
        performIpList = []
        for i in performIpLists:
            if i is not None:
                performIpList.append(i)
        performUser = ''
        environment = data['environment']
        caseStats = self.caseStatus(data['caseStatus'])  # case执行结果
        if caseStats == 1:
            imageListID = self.getImageID()
        url = config[Log_path]["uploadStatUrl"] + 'case/addCaseStats'
        json = {
            "id": "{}".format(id),
            "case_id": "{}".format(caseId),
            "case_name": "{}".format(caseName),
            "start_time": "{}".format(startTime),
            "end_time": "{}".format(endTime),
            "case_status": "{}".format(caseStats),
            "case_exception": "{}".format(caseException),
            "project_run_id": "{}".format(projectRunId),
            "project_version": "{}".format(projectVersion),
            "case_class": "{}".format(caseClass),
            "case_method": "{}".format(caseMethod),
            "case_description": "{}".format(caseDescription),
            "perform_ip": performIpList,
            "perform_user": "{}".format(performUser),
            "file_list": imageListID,
            "environment": "{}".format(environment)
        }
        print(json)
        response = requests.post(url, json=json)
        assert response.status_code == 200
        assert response.json()["code"] == 200
        return response.json()

    def upload_log(self, case_id=None, run_id=None, level=None, message=None):
        """
        测试log入库
        :param case_id:用侧id
        :param run_id:日志和测试报告的绑定id
        :param level:日志级别
        :param message:日东内容
        :return:响应结果
        """
        url = config[Log_path]["uploadStatUrl"] + 'log/addLog'
        json = {
            "case_id": "{}".format(case_id),
            "run_id": "{}".format(run_id),
            "content": "{}".format(message),
            "log_level": "{}".format(level)
        }
        response = http_post(url, json)
        assert response.status_code == 200
        assert response.json()["code"] == 200
        return response.json()

    def get_log(self, caseId):
        """
        获取测试log根据caseId获取对应的log信息
        :param caseId:用例id
        :return: log信息
        """

        url = config[Log_path]["uploadStatUrl"] + 'log/getCaseLogListByCaseId'
        json = {
            "case_id": "{}".format(caseId)
        }
        response = requests.post(url, json=json)
        assert response.status_code == 200
        assert response.json()["code"] == 200
        return response.json()

    def get_loglevel(self, caseId, level):
        """
        获取测试log根据caseId和level获取对应的log信息
        :param caseId:用例id
        :param level:log等级
        :return:log信息
        """
        url = config[Log_path]["uploadStatUrl"] + 'log/getCaseLogListByLevel'
        json = {
            "caseId": "{}".format(caseId),
            "logLevel": "f}".format(level)
        }
        response = requests.post(url, json=json)
        assert response.status_code == 200
        assert response.json()["code"] == 200
        return response.json()

    def get_report(self, caseId):
        """
        获取
        测
        试报告根据caseId获取对应的测试报告信
        :param caseId:用例id
        :return:测试报告信息
        """
        url = config[Log_path]["uploadStatUrl"] + 'case/getCaseStatsListByCaseId'
        json = {
            "c"
            "aseId": "{}".format(caseId)
        }
        response = requests.post(url, json=json)
        assert response.status_code == 200
        assert response.json()["code"] == 200
        return response.json()

    def get_Image(self, id):
        """
        获取测试报告根据caseId获取对应的测试报告信息
        :param id:图片id
        :return:图片信息
        """

        url = config[Log_path]["uploadStatUrl"] + 'file/getFileById'
        json = {
            "id": "{}".format(id)
        }
        response = requests.post(url, json=json)
        assert response.status_code == 200
        assert response.json()["code"] == 200
        return response.json()


if __name__ == '__main__':
    pass
